/**
 * Copyright 2009 Marc Stogaitis and Mimi Sun
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.gmote.server.media.basic;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.gmote.common.FileInfo;
import org.gmote.common.Protocol.Command;
import org.gmote.common.media.MediaMetaInfo;
import org.gmote.server.ServerUtil;
import org.gmote.server.media.MediaPlayerInterface;
import org.gmote.server.media.PlayerUtil;
import org.gmote.server.media.UnsupportedCommandException;

import android.os.IBinder;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.provider.MediaStore;
import android.view.IWindowManager;
import android.view.KeyEvent;

/**
 * Simple player that simply launches files in the operating system's default
 * player.
 * 
 * @author Marc Stogaitis
 */
public class AndroidMediaPlayer implements MediaPlayerInterface {
  private static final Logger LOGGER = Logger.getLogger(DefaultFilePlayer.class.getName());
  private boolean isRunning = false;
  IBinder wmbinder = ServiceManager.getService( "window" );
  final IWindowManager wm = IWindowManager.Stub.asInterface( wmbinder );  
  private void type(int code) {
	  try {
	  wm.injectKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, code), false);
	  wm.injectKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, code), false);
	  } catch (RemoteException e) {
		  e.printStackTrace();
	  }
  }
  public void controlPlayer(Command command) throws UnsupportedCommandException {
      if (command == Command.FAST_FORWARD || command == Command.FAST_FORWARD_LONG) {
    	  LOGGER.info("FAST_FORWARD");
    	  type(command == Command.FAST_FORWARD ? KeyEvent.KEYCODE_MEDIA_FAST_FORWARD : KeyEvent.KEYCODE_MEDIA_NEXT);
      } else if (command == Command.REWIND || command == Command.REWIND_LONG) {
    	  LOGGER.info("REWIND");
    		type(command == Command.REWIND ? KeyEvent.KEYCODE_MEDIA_REWIND : KeyEvent.KEYCODE_MEDIA_PREVIOUS);
      } else if (command == Command.CLOSE) {
        CommonOperations.sendCloseCommand();
        isRunning = false;
      } else if (command == Command.PLAY) {
        // Maximizes a window
    	  LOGGER.info("PLAY");
        
    	  type(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE);
      } else if (command == Command.PAUSE) {
    	  LOGGER.info("PAUSE");
    	  type(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE);
      } else if (command == Command.MUTE) {
    	  LOGGER.info("MUTE");
    	  type(KeyEvent.KEYCODE_MUTE);
      } else if (command == Command.VOLUME_UP) {
    	  LOGGER.info("VOLUME_UP");
    	  type(KeyEvent.KEYCODE_VOLUME_UP);
      } else if (command == Command.VOLUME_DOWN) {
    	  LOGGER.info("VOLUME_DOWN");
    	  type(KeyEvent.KEYCODE_VOLUME_DOWN);
      }

  }

  public List<FileInfo> getBaseLibraryFiles() {
    return null;
  }

  public List<FileInfo> getLibrarySubFiles(FileInfo fileInfo) {
    return null;
  }

  public MediaMetaInfo getNewMediaInfo() {
    return new MediaMetaInfo("", "File Viewer", "", PlayerUtil
        .loadImage("file.png"), false);
  }

  public void initialise(String[] arguments) {

  }
  
  private String getImageUri(String path) {
	  boolean isExternal = false;
	  String[] cmd = new String[3];
	  cmd[0] = "sqlite3";
	  cmd[1] = "/data/data/com.android.providers.media/databases/";
	  if (path.startsWith("/sdcard")) {
		  cmd[1] = cmd[1] + "internal.db";
		  isExternal = false;
	  }
	  else if (path.startsWith("/mnt/extsd")) {
		  cmd[1] = cmd[1] + "external.db";
		  isExternal = true;
	  }
	  cmd[2] = "select _id from images where _data=\"" + path + "\"";
	try {
		Process proc = Runtime.getRuntime().exec(cmd);
		BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
		String id = br.readLine();
		LOGGER.info("Path="+path+",ID="+id);
		if (isExternal) {
			return MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString() + "/" + id;
		}
		else {
			return MediaStore.Images.Media.INTERNAL_CONTENT_URI.toString() + "/" + id;
		}
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return null;
  }

  public void runFile(FileInfo fileInfo) throws UnsupportedEncodingException,
      UnsupportedCommandException {
	  String[] cmd;
	  
	  switch (fileInfo.getFileType()) {
	  case MUSIC:
		  String[] mcmd = { "am", "start", "-d", "file://" + fileInfo.getAbsolutePath(), "com.android.music/.MediaPlaybackActivity" };
		  cmd = mcmd;
		  break;
	  case IMAGE:
		  String uri = getImageUri(fileInfo.getAbsolutePath());
		  LOGGER.info("imaeg uri="+uri);
		  String[] icmd = { "am", "start", "-a", "android.intent.action.VIEW",
				                           "-d", uri,
				                           "-t", "image/*"};
		  cmd = icmd;
		  break;
	  case VIDEO:
		  String[] vcmd = { "am", "start", "-a", "android.intent.action.VIEW",
                                           "-d", "file://" + fileInfo.getAbsolutePath(),
                                           "-t", "video/*"};
		  cmd = vcmd;
		  break;
	  default:
		  isRunning = false;
		  return;
	  }
	  
	  try {
		Runtime.getRuntime().exec(cmd);
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
    isRunning = true;
  }

  public boolean isRunning() {
    return isRunning;
  }

}
